import {
	config
} from "./config";

// 非流式对话
export function singleTalk(messages) {
	return uni.request({
		url: config.GLM_URL,
		method: "POST",
		data: {
			model: "glm-4v-flash",
			messages: messages,
			temperature: 0,
			max_tokens: 5,
		},
		header: {
			'Authorization': `Bearer ${config.API_KEY}`,
			"Content-Type": "application/json;charset=UTF-8;",
		}
	})
}

// 多轮流式对话
export function multiTalk(messages) {
	return getTalk(messages)
}

// 解码
export function decodeStream(content, dispose) {
	const uint8Array = new Uint8Array(content);
	// 使用兼容写法解码
	const str = decodeURIComponent(escape(String.fromCharCode(...uint8Array)));
	const regex = /data:\s*(.*)/g;
	let match;
	while ((match = regex.exec(str)) !== null) {
		if (match[1] != '[DONE]' && match[1] != ' ') {
			// console.log(JSON.parse(match[1]).choices[0].delta.content);
			dispose(JSON.parse(match[1]).choices[0].delta.content)
		}
		if (match[1] == '[DONE]') {
			dispose(undefined, true)
		}
	}
}


// 请求函数(无需导出)
function getTalk(messages) {
	return uni.request({
		url: config.GLM_URL,
		method: "POST",
		data: {
			model: "glm-4",
			messages: messages,
			stream: true
		},
		enableChunked: true, // 开启分块传输
		responseType: "text",
		header: {
			'Authorization': `Bearer ${config.API_KEY}`,
			"Content-Type": "application/json;charset=UTF-8;",
		},
		success: (res) => {
			// resolve(res)
		},
		fail: (err) => {
			reject(err)
		},
	});
}